//  Parameter details refer to:https://support.huaweicloud.com/api-elb/elb_qy_fz_0001.html
//  Create an ELB service
resource  "huaweicloud_lb_loadbalancer" "loadbalancer" {
  count = var.is_elb_creat ? 1 : 0
  name          = var.name_suffix != null ? format("%s-%s", var.loadbalancer_name, var.name_suffix) : var.loadbalancer_name
  vip_subnet_id = var.ipv4_subnet_id
  tags = merge(
    { "Name" = var.name_suffix != null ? format("%s-%s", var.loadbalancer_name, var.name_suffix) : var.loadbalancer_name},
    var.loadbalancer_tags)
}

//  Create a listener
resource "huaweicloud_lb_listener" "listener" {
  count = var.is_elb_creat ? 1 : 0
  name            = var.name_suffix != null ? format("%s-%s", var.listener_name, var.name_suffix) : var.listener_name
  //  Front-end protocol
  protocol        = var.listener_protocol
  //  Protocol port
  protocol_port   = var.protocol_port
  loadbalancer_id = huaweicloud_lb_loadbalancer.loadbalancer[0].id
  tags = merge(
    { "Name" = var.name_suffix != null ? format("%s-%s", var.listener_name, var.name_suffix) : var.listener_name},
    var.listener_tags)
}

//  Create a pool
resource "huaweicloud_lb_pool" "pool" {
  count = var.is_elb_creat ? 1 : 0
  listener_id     = huaweicloud_lb_listener.listener[0].id
  name            = var.pool_name
  //  Backend protocol
  protocol        = var.pool_protocol
  //  Assign the policy type
  lb_method       = var.lb_method
}

//  Create a security check feature for the back-end server
resource "huaweicloud_lb_monitor" "monitor" {
  count = var.is_elb_creat ? 1 : 0
  pool_id     = huaweicloud_lb_pool.pool[0].id
  //  Health check protocol type
  type        = var.monitor_type
  //Health check interval (in seconds)
  delay       = var.monitor_delay
  //  Health check timeout (in seconds)
  timeout     = var.monitor_timeout
  //  Maximum number of health check retries (option 1~10)
  max_retries = var.monitor_max_retries
  url_path    = var.url_path
}

//  Create a back-end server-to-server binding
resource "huaweicloud_lb_member" "member" {
  
  count = var.member_configuration != null ? length(var.member_configuration) : 0
  address       = lookup(element(var.member_configuration, count.index), "address")
  //  Protocol port
  protocol_port = var.protocol_port
  pool_id       = huaweicloud_lb_pool.pool[0].id
  subnet_id     = var.ipv4_subnet_id
  //  Configure the weight, which is 1 by default
  weight        = lookup(element(var.member_configuration, count.index), "weight")
}
